package com.huatai.datacenter.utils;

import com.alibaba.fastjson.JSONObject;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author gusiyi
 * @version 1.0
 * @className KeyGeneratorUtils
 * @description 描述：加密密钥生成工具类
 * @date 2023/6/14 16:45
 */
public class KeyGeneratorUtils {

	private static final String AES_ALGORITHM = "AES";
	private static final String DES_ALGORITHM = "DES";

	/**
	 * 生成对称算法密钥
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String generateKey(String algorithm) throws NoSuchAlgorithmException {
		if (algorithm.equals(AES_ALGORITHM)) {
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			keyGenerator.init(128);
			SecretKey secretKey = keyGenerator.generateKey();
			return Base64.getEncoder().encodeToString(secretKey.getEncoded());
		}else if (algorithm.equals(DES_ALGORITHM)){
			KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
			keyGenerator.init(56);
			SecretKey secretKey = keyGenerator.generateKey();
			return Base64.getEncoder().encodeToString(secretKey.getEncoded());
		}else {
			throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
		}
	}

	public static String generateAllKey() throws Exception {
		String aesKey = generateKey(AES_ALGORITHM);
		String desKey = generateKey(DES_ALGORITHM);
		KeyPair rsaKeyPair = RSAUtils.generateKeyPair(2048);
		JSONObject keyJson = new JSONObject();
		keyJson.put("AESKey",aesKey);
		keyJson.put("DESKey",desKey);
		byte[] publicKeyBytes = rsaKeyPair.getPublic().getEncoded();
		byte[] privateKeyBytes = rsaKeyPair.getPrivate().getEncoded();
		String rsaPublicKey = Base64.getEncoder().encodeToString(publicKeyBytes);
		String rsaPrivateKey = Base64.getEncoder().encodeToString(privateKeyBytes);
		keyJson.put("RSAPublicKey",rsaPublicKey);
		keyJson.put("RSAPrivateKey",rsaPrivateKey);
		return keyJson.toJSONString();
	}

}
